﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Library.IniFiles
{
    public class IniFileRewrite
    {
        private FileInfo _file;
        private Dictionary<string, Dictionary<string, string>> _changes = new Dictionary<string, Dictionary<string, string>>();

        public IniFileRewrite()
        {
        }

        public IniFileRewrite(FileInfo file)
        {
            this._file = file;
        }

        public void UpdateEntry(string section, string key, string val)
        {
            Dictionary<string, string> items;
            if (!_changes.ContainsKey(section))
            {
                items = new Dictionary<string, string>();
                _changes[section] = items;
            }
            else
            {
                items = _changes[section];
            }
            items[key] = val;
        }

        public void UpdateEntries(string section, Dictionary<string, string> newItems)
        {
            Dictionary<string, string> items;
            if (!_changes.ContainsKey(section))
            {
                items = new Dictionary<string, string>();
                _changes[section] = items;
            }
            else
            {
                items = _changes[section];
            }

            foreach (string key in items.Keys) items[key] = items[key];
        }

        public void ApplyChanges(FileInfo file)
        {
            this._file = file;
            this.ApplyChanges();
        }

        public void ApplyChanges()
        {
            if (_file != null)
            {
                if (!_file.Exists)
                {
                    using (StreamWriter w = _file.CreateText())
                    {
                        foreach (string section in _changes.Keys)
                        {
                            w.WriteLine("[" + section + "]");
                            Dictionary<string, string> pair = _changes[section];
                            foreach (string key in pair.Keys)
                            {
                                string val = pair[key];
                                if (val.IndexOf('\"') >= 0) val = "\"" + val.Replace("\"", "\"\"") + "\"";
                                w.WriteLine(key + "=" + val);
                            }
                        }
                        w.Flush();
                        w.Close();
                    }
                }
                else
                {
                    FileInfo temp = new FileInfo(Path.GetTempFileName());
                    using (StreamWriter w = _file.CreateText())
                    {
                        using (StreamReader r = _file.OpenText())
                        {
                            string currentSection = string.Empty;
                            Dictionary<string, string> pairs = null;
                            string line = r.ReadLine(), currentKey = null;
                            while (line != null)
                            {
                                if (line.StartsWith(";")) // Comment
                                {
                                    if (line.StartsWith("[")) // Section
                                    {
                                        if ((pairs != null) && (pairs.Count > 0))
                                        {
                                            foreach (string key in pairs.Keys)
                                            {
                                                string val = pairs[key];
                                                if (val.IndexOf('\"') >= 0) val = "\"" + val.Replace("\"", "\"\"") + "\"";
                                                w.WriteLine(key + "=" + val);
                                            }
                                            pairs.Clear();
                                            pairs = null;
                                        }

                                        currentSection = line.Trim('\t', ' ', '[', ']');
                                        if (_changes.ContainsKey(currentSection))
                                            pairs = _changes[currentSection];
                                    }
                                    else 
                                    {
                                        int idx = line.IndexOf("=");
                                        if (idx > 0) // Key Value Pair
                                        {
                                            currentKey = line.Substring(0, idx).Trim();
                                        }
                                    }
                                }

                                if ((pairs != null) && (pairs.ContainsKey(currentKey)))
                                {
                                    string val = pairs[currentKey];
                                    if (val.IndexOf('\"') >= 0) val = "\"" + val.Replace("\"", "\"\"") + "\"";
                                    w.WriteLine(currentKey + "=" + val);

                                    pairs.Remove(currentKey);
                                }
                                else
                                {
                                    w.WriteLine(line);
                                }

                                line = r.ReadLine();
                            }
                            r.Close();
                        }
                        w.Flush();
                        w.Close();
                    }
                    temp.MoveTo(_file.FullName);
                    _file.Refresh();
                }

            }
        }
    }
}
